<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>AI 助手 - 集成豆包AI</title>
  <link rel="stylesheet" href="../../layui/css/layui.css">
  <script src="../../layui/layui.js"></script>
  <script src="../../js/config.js"></script>
  <script src="../../modules/config.js"></script>
</head>
<body>
<h2>AI 助手</h2>
<div id="chatBox"></div>
<input type="text" id="userInput" placeholder="请输入问题..." style="width: 70%;">
<button onclick="sendMsg()">发送</button>

<script>
  const chatBox = document.getElementById('chatBox');
  let http = null; // 声明全局http对象
  const layer = layui.layer;

  function sendMsg() {
    const input = document.getElementById('userInput');
    const msg = input.value.trim();
    if (!msg) {
      layer.msg('请输入问题', {icon: 5});
      return;
    }

    // 显示用户消息
    chatBox.innerHTML += `<div class="msg user">👤 你：${msg}</div>`;
    input.value = '';
    chatBox.scrollTop = chatBox.scrollHeight;

    // 确保http已加载
    if (!http) {
      layer.msg('服务加载中，请稍候...', {icon: 16});
      return;
    }

    // 调用AI服务
    callAiService(msg);
  }

  layui.use(['http', 'layer'], function() {
    http = layui.http; // 初始化http对象
    const layer = layui.layer;

    // 获取上下文路径，解决404问题
    const contextPath = window.contextPath || '';
    const apiUrl = 'http://localhost:8080/tiyuguanguanli/api/ai/chat'; // 修改为正确的路径

    function callAiService(question) {
      // 显示加载状态
      chatBox.innerHTML += `<div class="msg ai">🤖 AI：正在思考中...</div>`;
      chatBox.scrollTop = chatBox.scrollHeight;

      // 获取上下文路径，解决 404 问题
      const contextPath = window.contextPath || '';
      const apiUrl = 'http://localhost:8080/tiyuguanguanli/api/ai/chat'; // 修改为正确的路径

      console.log(`请求发送: ${question}`);

      // 使用 fetch 发送请求
      fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Token': localStorage.getItem('Token')  // 从 localStorage 中获取 Token 并添加到请求头
        },
        body: JSON.stringify({ question: question })
      })
              .then(response => response.json())
              .then(res => {
                console.log('响应成功:', res);
                if (res.success) {
                  const answer = res.answer || '抱歉，我无法回答';
                  updateChatBox(answer);
                } else {
                  layer.msg(res.errorMessage || '获取AI回答失败', { icon: 5 });
                  updateChatBox('抱歉，我遇到了问题，无法回答');
                }
              })
              .catch(err => {
                console.error('网络请求失败:', err);
                layer.msg('网络请求失败，请检查网络连接', { icon: 5 });
                updateChatBox('抱歉，网络请求失败');
              });

    }


    // 更新聊天框内容
    function updateChatBox(answer) {
      const messages = chatBox.innerHTML;
      const lastIndex = messages.lastIndexOf('AI：正在思考中...');
      if (lastIndex > 0) {
        const newMessages = messages.substring(0, lastIndex) +
                `<div class="msg ai">🤖 AI：${answer}</div>`;
        chatBox.innerHTML = newMessages;
      } else {
        chatBox.innerHTML += `<div class="msg ai">🤖 AI：${answer}</div>`;
      }
      chatBox.scrollTop = chatBox.scrollHeight;
    }

    // 暴露方法到全局作用域
    window.sendMsg = sendMsg;
    window.callAiService = callAiService;
  });
</script>
<style>
  /* 样式保持不变 */
  body { padding: 20px; font-family: Arial; }
  #chatBox { height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; }
  .msg { margin: 5px 0; }
  .user { color: blue; }
  .ai { color: green; }
  body {
    padding: 30px;
    font-family: "Microsoft YaHei", sans-serif;
    background: #f6f8fa;
  }

  #chatBox {
    height: 400px;
    background: #fff;
    overflow-y: auto;
    border-radius: 8px;
    border: 1px solid #ddd;
    padding: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 15px;
  }

  .msg {
    margin: 10px 0;
    line-height: 1.6;
  }

  .user {
    color: #2b7cff;
    font-weight: bold;
  }

  .ai {
    color: #28a745;
    font-weight: bold;
  }

  input#userInput {
    width: 70%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }

  button {
    padding: 10px 18px;
    background: #2b7cff;
    color: #fff;
    border: none;
    border-radius: 4px;
    margin-left: 10px;
    cursor: pointer;
    transition: background 0.3s ease;
  }

  button:hover {
    background: #1a5ed0;
  }
</style>
</body>
</html>